/*
 * key.c
 *
 *  Created on: Apr 11, 2012
 *      Author: Tri_D
 */

#include "key.h"
#include "serial.h"


void init_button(Button_t * pB, Button_ID_t Id)
{
	pB->ID = Id;
	pB->Rebounce = 0;
	pB->bPress = 0;
	pB->holdtimer = 0;
}


void init_keybrd(KeyBrd_t * pK)
{
	init_button(&pK->Zero, ZERO_BUTTON);
	init_button(&pK->Tare, TARE_BUTTON);
	init_button(&pK->Net, NET_BUTTON);
	init_button(&pK->Unit, UNIT_BUTTON);
	init_button(&pK->Fn, FN_BUTTON);
	init_button(&pK->Print, PRINT_BUTTON);
	pK->Intent = NO_INTENT;
}


/*
 * Provided the 6 button intent. 
 * Decode and return the keyboard intent
 */
Key_Intent_t decode_intent(Key_Intent_t * pI)
{
	Key_Intent_t intent_ = NO_INTENT;
	uint8_t c;
	
	for(c = 0; c < 6; c++)
	{
		if (intent_ == NO_INTENT)
		{
			if (pI[c] != NO_INTENT)
				intent_ = pI[c];
		}
		else if (intent_ == UNIT_INTENT)			// keypress Unit and Fn regardless of how long holding down			
		{
			if (pI[c] == FN_INTENT)
				intent_ = SETUP_INTENT;
		}
		else if (intent_ == TARE_INTENT)			
		{
			if (pI[c] == PRINT_INTENT)				// Print tare	Tare and Print send <lf>M<cr>
				intent_ = PRINT_TARE_INTENT;			
			else if (pI[c] == FN_INTENT)			// Tare and Fn to send <lf>C<cr> .. Clear Tare
				intent_ = CLEAR_TARE_INTENT; 
		}				
	}
	return intent_;
}


/* 
 * Scane keyboard for key press sequences and identify intents
 */
void scan_keybrd(KeyBrd_t * pK)
{
	Key_Intent_t c[6];
	uint8_t c1;	
	
	for(c1=0;c1<6;c1++)
		c[c1] = NO_INTENT;
	// Check Zero key
	if (pK->Zero.bPress == 3)
	{
		pK->Zero.bPress = 0;
		// To check for holding down keys, look at holdtimer values to change the button intent
		c[0] = ZERO_INTENT;
	}
	// Check Tare key
	if (pK->Tare.bPress == 3)
	{
		pK->Tare.bPress = 0;
		c[1] = TARE_INTENT;
	}
	// Check Net key
	if (pK->Net.bPress == 3)
	{
		pK->Net.bPress = 0;
		c[2] = NET_INTENT;
	}
	// Check Unit key
	if (pK->Unit.bPress ==3)
	{
		pK->Unit.bPress = 0;
		c[3] = UNIT_INTENT;
	}
	// Check Fn key
	if (pK->Fn.bPress == 3)
	{
		pK->Fn.bPress = 0;
		c[4] = FN_INTENT;
	}
	// Check Print key
	if (pK->Print.bPress == 3)
	{
		pK->Print.bPress =0;
		c[5] = PRINT_INTENT;
	}
	pK->Intent = decode_intent(c);
}
